package com.lanou.renrenxin.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.FileMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.NetUtils;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.adapter.TabAdapter;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.base.BaseApplication;
import com.lanou.renrenxin.custommodule.NoScrollViewPager;
import com.lanou.renrenxin.dao.ChatList;
import com.lanou.renrenxin.fragment.ChatFragment;
import com.lanou.renrenxin.fragment.FriendFragment;
import com.lanou.renrenxin.fragment.PersonalFragment;
import com.lanou.renrenxin.fragment.SetFragment;
import com.lanou.renrenxin.mybomb.Invitation;
import com.lanou.renrenxin.singleton.RenrenxinSingleton;
import com.lanou.renrenxin.tools.Constant;
import com.lanou.renrenxin.tools.LogUtils;
import com.lanou.renrenxin.tools.RenRenXinHelper;
import com.lanou.renrenxin.tools.StringValues;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class MainActivity extends BaseActivity {
    private ArrayList<Fragment> fragments;
    private NoScrollViewPager viewPager;
    private RadioGroup tabRadioGroup;
    private RadioButton chatRadioBtn;
    private TabAdapter tabAdapter;
    private Handler handler;
    private String mUserName = new String();
    private String s;
    private NewMessageBroadcastReceiver msgReceiver;
    private Button btnAdd, btnSearch,btnCreat;
    // 账号在别处登录
    public boolean isConflict = false;
    // 账号被移除
    private boolean isCurrentAccountRemoved = false;
    private Invitation invitation;

    /**
     * 检查当前用户是否被删除
     */
    public boolean getCurrentAccountRemoved() {
        return isCurrentAccountRemoved;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());

        RenrenxinSingleton.getInstence().loadHeadImage(mUserName);

        findId();
        loadData();
        mUserName = getIntent().getStringExtra("LOGIN_USER_NAME");
        //只有注册了广播才能接收到新消息，目前离线消息，在线消息都是走接收消息的广播（离线消息目前无法监听，在登录以后，接收消息广播会执行一次拿到所有的离线消息）
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        loadData();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;

    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        RenRenXinHelper.getInstance().logout(false, null);
        String str = getResources().getString(R.string.logoff_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new AlertDialog.Builder(MainActivity.this);
                conflictBuilder.setTitle(str);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        conflictBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {

            }
        }
    }

    /**
     * 帐号被移除的dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        RenRenXinHelper.getInstance().logout(false, null);
        String st = getResources().getString(R.string.remove_the_notification);

        if (!MainActivity.this.isFinishing()) {
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new AlertDialog.Builder(MainActivity.this);
                accountRemovedBuilder.setTitle(st);
                accountRemovedBuilder.setMessage(R.string.em_user_remove);
                accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        accountRemovedBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {

            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(msgReceiver);
    }

    private void findId() {
        viewPager = (NoScrollViewPager) findViewById(R.id.viewPager_activity_main);
        tabRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_activity_main_tab);
        chatRadioBtn = (RadioButton) findViewById(R.id.radioBtn_activity_main_chat);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        btnCreat = (Button) findViewById(R.id.btnCreat);
    }

    private void loadData() {
        invitation = new Invitation();

        fragments = new ArrayList<>();
        ChatFragment chatFragment = new ChatFragment();
        FriendFragment friendFragment = new FriendFragment();
        fragments.add(chatFragment);
        fragments.add(friendFragment);
        fragments.add(new PersonalFragment());
        fragments.add(new SetFragment());


        Bundle bundle = new Bundle();
        bundle.putString("USER_NAME_MAIN", mUserName);
        bundle.putString("TO_USERNAME", s);
        chatFragment.setArguments(bundle);
        friendFragment.setArguments(bundle);

        tabAdapter = new TabAdapter(getSupportFragmentManager(), fragments, BaseApplication.getContext());
        viewPager.setAdapter(tabAdapter);
        viewPager.setCurrentItem(0, true);
        chatRadioBtn.setChecked(true);
        tabRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioBtn_activity_main_chat:
                        viewPager.setCurrentItem(0, false);
                        break;
                    case R.id.radioBtn_activity_main_friend:
                        viewPager.setCurrentItem(1, false);
                        break;
                    case R.id.radioBtn_activity_main_personal:
                        viewPager.setCurrentItem(2, false);
                        break;
                    case R.id.radioBtn_activity_main_set:
                        viewPager.setCurrentItem(3, false);
                        break;
                }
            }
        });

        btnAdd.setVisibility(View.GONE);
        btnSearch.setVisibility(View.GONE);
        btnCreat.setVisibility(View.GONE);

        addContact();
    }

    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 截断广播
            abortBroadcast();
            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            ChatList chat = new ChatList();
            String body = "";
            String msgType = "";

            if (message.getType() == EMMessage.Type.TXT) {
                msgType = StringValues.MSG_TYPE_TXT;
                body = ((TextMessageBody) message.getBody()).getMessage();
            } else if (message.getType() == EMMessage.Type.FILE) {
                body = "[文件]"+((FileMessageBody)message.getBody()).getFileName();
                msgType = StringValues.MSG_TYPE_FILE;
            } else if (message.getType() == EMMessage.Type.IMAGE) {
                msgType = StringValues.MSG_TYPE_IMAGE;
                body = "[图片]";
            } else if (message.getType() == EMMessage.Type.LOCATION) {
                msgType = StringValues.MSG_TYPE_LOCATION;
                body = "[位置]"+((LocationMessageBody)message.getBody()).getAddress();
            } else if (message.getType() == EMMessage.Type.VOICE) {
                msgType = StringValues.MSG_TYPE_VOICE;
                body = "[语音]";
            } else if (message.getType() == EMMessage.Type.VIDEO) {
                msgType = StringValues.MSG_TYPE_VIDEO;
            }
            chat.setBody(body);
            chat.setMsg_type(msgType);
            chat.setUsername(message.getUserName());
            chat.setMUsername(username);
            chat.setType(1);
            RenrenxinSingleton.getInstence().saveChatList(chat);
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
        }
    }

    private void addContact() {
        EMContactManager.getInstance().setContactListener(new EMContactListener() {

            @Override
            public void onContactAgreed(String username) {
                //好友请求被同意
                Log.e("ççççççç", "同意好友");
                BmobQuery<Invitation> query = new BmobQuery<Invitation>();
                query.addWhereEqualTo("friendUsername", username);
                query.addWhereEqualTo("username", mUserName);
                query.findObjects(MainActivity.this, new FindListener<Invitation>() {
                    @Override
                    public void onSuccess(List<Invitation> list) {
                        Log.e("MainActivity", "list.size():" + list.size());
                        for (Invitation i : list) {
                            LogUtils.e("ObjectId", i.getObjectId());
                            invitation.setIsAgree(true);
                            invitation.update(MainActivity.this, i.getObjectId(), new UpdateListener() {
                                @Override
                                public void onSuccess() {
                                    LogUtils.e("MainActivity", "同意好友保存成功");
                                }

                                @Override
                                public void onFailure(int i, String s) {

                                }
                            });
                        }
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });

            }

            @Override
            public void onContactRefused(String username) {
                //好友请求被拒绝
                invitation.setUsername(mUserName);
                invitation.setFriendUsername(username);
                invitation.setIsAgree(false);
                invitation.setIsRefuse(true);
                invitation.update(MainActivity.this, new UpdateListener() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
            }

            @Override
            public void onContactInvited(final String username, String reason) {
                //收到好友邀请
                Log.e("AddContactActivity", username + "想加你");
                invitation.setUsername(mUserName);
                invitation.setFriendUsername(username);
                invitation.setReason(reason);
                invitation.setIsAgree(false);
                invitation.setIsRefuse(false);
                invitation.save(MainActivity.this, new SaveListener() {
                    @Override
                    public void onSuccess() {
                        Intent intent = new Intent();
                        intent.setAction(StringValues.ACTION_NEW_INVITATION);
                        intent.putExtra("FRIEND_NAME", username);
                        sendBroadcast(intent);
                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
            }

            @Override
            public void onContactDeleted(List<String> usernameList) {
                //被删除时回调此方法
            }


            @Override
            public void onContactAdded(List<String> usernameList) {
                //增加了联系人时回调此方法
            }
        });
    }

    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
            //已连接到服务器
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (error == EMError.CONNECTION_CONFLICT) {
                        showConflictDialog();
                    } else if (error == EMError.USER_REMOVED) {
                        showAccountRemovedDialog();
                    } else if (NetUtils.hasNetwork(MainActivity.this)) {
                        Toast.makeText(MainActivity.this, "连接不到聊天服务器", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "当前网络不可用！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
}



